package com.pic.mgt.monitor.parser;

import java.io.File;

import org.apache.commons.lang.StringUtils;

import com.pic.mgt.executer.SimpleConfirmationFileMaker;
import com.pic.mgt.monitor.WrongUnitFormatException;

/**
 * 此 Parser 用途是給定 Message 的 Confirmation Filename，分析後回傳 Message 交易檔對應的 Confirmation File。
 * @author p10118178
 *
 */
public final class ConfirmtaionFileForTxFileParser extends FormatParser {
	private static String businessConfirmationFilenameSuffix;
	
	private FormatParser transactionFileParser;

	@Override
	/**
	 * 此 Parser 用途是給定 Message 的 Confirmation File，分析後回傳 Message 交易檔對應的 Confirmation File。
	 */
	public Object parse(Object _confirmationFile) throws WrongUnitFormatException {
		// 確認是否為 File 型態
		// throws WrongUnitFormatException
		super.checkObjectType(_confirmationFile, File.class);
		
		File confirmationFile = (File)_confirmationFile;
		
		// 取得交易檔
		// throws WrongUnitFormatException
		File trnasactionFile = (File)this.transactionFileParser.parse(confirmationFile);
		
		// 得到交易檔對應的 Confirmation File
		File confirmationFileForTxFile = getConfirmationFile(trnasactionFile);
		
		if (!confirmationFileForTxFile.exists()) {
			/*
			 *  注意!!! 如果要修改訊息拋出內容要小心!! 因為會有其它類別依照此訊
			 *  息內容來作為一些判斷的準則。
			 */
			throw new WrongUnitFormatException(
								"Confirmation file '" + confirmationFileForTxFile.getName() +
								"' for transaction file doesn't exist.");
		}
		
		return confirmationFileForTxFile;
	}
	
	/**
	 * 取得確認檔對應的交易檔
	 * @param confirmationFile
	 * @return
	 */
	public static File getTransactionFile(File confirmationFile) {
		return new File(StringUtils.substringBefore(
				                 confirmationFile.getAbsolutePath(),
						         businessConfirmationFilenameSuffix));
	}
	
	/**
	 * 取得交易檔對應的確認檔.
	 * @param transactionFile
	 * @return
	 */
	public static File getConfirmationFile(File transactionFile) {
		return
			new File(transactionFile.getAbsolutePath() + 
					 businessConfirmationFilenameSuffix);
	}
	
	/**
	 * 取得確認檔的暫存檔
	 * @param confirmationFile
	 * @return
	 */
	public static File getTmpConfirmationFile(File confirmationFile) {
		return
			new File(confirmationFile.getAbsolutePath() +
					 SimpleConfirmationFileMaker.tmpFileOkSuffixString);
	}
	
	// --- getter and setter ---

	public void setBusinessConfirmationFilenameSuffix(String bizsConfirmationFilenameSuffix) {
		businessConfirmationFilenameSuffix = bizsConfirmationFilenameSuffix;
	}

	public void setTransactionFileParser(FormatParser transactionFileParser) {
		this.transactionFileParser = transactionFileParser;
	}

}
